package com.yudaob2b.elong.task;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.yudaob2b.business.entity.po.ElongHotelInventoryPO;
import com.yudaob2b.business.service.ElongHotelInventoryService;
import com.yudaob2b.elong.entity.vo.IncrInventory;
import com.yudaob2b.elong.service.HotelInventoryService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 库存增量同步线程任务
 *
 * @author Kidd.Tan
 * @email 298023780@qq.com
 * @date 7/20/18 8:42 PM
 */
public class IncrInvDbTask implements Runnable, Serializable {
    private static Logger incrInvLogger = LoggerFactory.getLogger("incrInvLogger");

    /**
     * 酒店id，最多10个
     */
    private List<IncrInventory> inctInvList;
    private ElongHotelInventoryService elongHotelInventoryService;
    private HotelInventoryService hotelInventoryService;

    public IncrInvDbTask(List<IncrInventory> inctInvList, ElongHotelInventoryService elongHotelInventoryService) {
        this.inctInvList = inctInvList;
        this.elongHotelInventoryService = elongHotelInventoryService;
        this.hotelInventoryService = hotelInventoryService;
    }

    @Override
    public void run() {
        long start = System.currentTimeMillis();

        // 待更新列表
        List<ElongHotelInventoryPO> updateList = new ArrayList();
        // 缓存就酒店库存列表
        List<ElongHotelInventoryPO> oldElongHotelInvList = null;
        String hotelIdTemp = "";
        for (IncrInventory incrInventory : inctInvList) {
            if (StringUtils.isEmpty(hotelIdTemp) || !hotelIdTemp.equals(incrInventory.getHotelID())) {
                EntityWrapper<ElongHotelInventoryPO> ew = new EntityWrapper<>();
                ew.where("hotel_id={0}", incrInventory.getHotelID());
                oldElongHotelInvList = elongHotelInventoryService.selectList(ew);
            }

            // 检查当前ElongHotelInventoryPO是否已经存在
            if (oldElongHotelInvList != null && oldElongHotelInvList.size() > 0) {
                int flag = 0;
                for (ElongHotelInventoryPO cacheInv : oldElongHotelInvList) {
                    if (cacheInv.getHotelId().equals(incrInventory.getHotelID())
                            && cacheInv.getRoomTypeId().equals(incrInventory.getRoomTypeId())
                            && cacheInv.getHotelCode().equals(incrInventory.getHotelCode())
                            && cacheInv.getDate().compareTo(incrInventory.getDate()) == 0) {
                        updateList.add(hotelInventoryService.getPoByInventory(incrInventory));
                        break;
                    }
                }
            }
        }

        if (updateList.size() > 0) {
            elongHotelInventoryService.updateBatch(updateList);
        }
        incrInvLogger.info("---库存增量线程总耗时：---{}", System.currentTimeMillis() - start);
    }
}
